<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8" />
		<title>Excel文件读取</title>
		<!-- import CSS -->
		<link rel="stylesheet" href="./style/element-ui@2.15.13.css" />
	</head>
	<body>
		<div id="app">
			<div>
				请选择一个Excel文件
			</div>
			<input id="btnFileInput"
				type="file"
				accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
				@change="handleUpload" />
			
			<el-row>
				<el-tabs v-model="mSelectedIndex">
					<el-tab-pane v-for="dt in mDataSet.Tables" :name="dt.TableName" :label="dt.TableName" >
						<el-table
						:height="480"
						:data="dt.Data"
						border
						style="width: 100%">							
							<el-table-column v-if="dt.Data" prop="ExcelRowNumber" label="行号" width="70" align="right"></el-table-column>
							<el-table-column v-for="column in dt.Columns" :prop="column.prop" :label="column.label">
							</el-table-column>
						</el-table>	
					</el-tab-pane>
				</el-tabs>
			</el-row>

			<div class="mt-2">
				<el-button @click="exportExcelFile">导出XLSX ( XLSX.utils.aoa_to_sheet 传入的参数必须是 二维数组 )</el-button>
			</div>
			<div class="mt-2">
				<el-button @click="arrayExportExcelFile">导出XLSX ( 使用 arrayToSheet )</el-button>
			</div>
		</div>
	</body>
	<!-- import Vue before Element -->
	<script src="./script/vue@2.7.14.js"></script>
	<!-- import JavaScript -->
	<script src="./script/element-ui@2.15.13.js"></script>
	
	<!-- import Excel类库 -->
	<script src="./script/xlsx.core.min@0.18.5.js"></script>
	<script src="./script/ExcelUtils@0.0.2.js"></script>

	<script>
		let app = new Vue({
			el: "#app",
			data: function () {
				return {
					mSelectedIndex: "",
					mDataSet: { Tables: null },
				};
			},
			methods: {
				handleUpload(event) {
					console.log("event:", event);
					console.log("event.target:", event.target);

					let component = event.target; // 控件对象被保存在 event.target 和 event.srcElement 中
					console.log("用户确认了选择文件。", component.files);
					console.log(`共选择 ${component.files.length} 份文件`);
					console.log("属性 files 的类型", Object.prototype.toString.call(component.files)); // 属性 files 的类型为 FileList
					
					let that = this;

					for (let index = 0; index < component.files.length; index++) {
						// 只用一个fileReader读取多个文件时会报错 Uncaught DOMException: Failed to execute 'readAsText' on 'FileReader': The object is already busy reading Blobs.
						// 所以需要new出多个 FileReader
						let fileReader = new FileReader();

						let selectedFile = component.files[index];
						fileReader.readAsBinaryString(selectedFile);
						fileReader.onload = function (event_onload) {
							// 当文件读取完成时，FileReader对象的onload事件会被触发。
							// 这个事件的处理函数会被执行，而且它的this.result属性会包含读取的文件内容。
							let ds = ExcelUtils.workBook2DataSet(this.result);
							console.log("DataSet: ", ds);
							
							that.mDataSet = ds;
							that.mSelectedIndex = ds.Tables[0].TableName;
						};
					}

					console.log("target.value: ", event.target.value);
					// !!!坑点!!! 如果连续两次导入的文件路径一致, 则不会触发 change 事件
					event.target.value = null;
				},

				exportExcelFile() {
					// 创建一个新的工作簿
					let workBook = XLSX.utils.book_new();

					// 二维数组 TestOutputTable0, TestOutputTable1
					const TestOutputTable0 = [
						["姓名", "年龄", "城市", "备注", "注册日期时间"],
						["张三", 28, "北京", null, new Date().toLocaleString()],
						["李四", 22, "上海", null, new Date().toLocaleString()],
						["王五", 35, "广州", "喜欢编程", new Date().toLocaleString()],
					];

					const TestOutputTable1 = [
						["ID", "姓名", "性别"],
						["小牛", 1, "男"],
						["小南", 2, "男"],
						["小芳", 3, "女"]
					];

					// XLSX.utils.aoa_to_sheet 传入的参数必须是 二维数组
					let workSheet0 = XLSX.utils.aoa_to_sheet(TestOutputTable0);
					let workSheet1 = XLSX.utils.aoa_to_sheet(TestOutputTable1);

					// 把工作表添加到工作簿
					XLSX.utils.book_append_sheet(workBook, workSheet0, "Sheet1");
					XLSX.utils.book_append_sheet(workBook, workSheet1, "Sheet2");

					// 导出 Excel 文件
					XLSX.writeFile(workBook, `example_${Date.now()}.xlsx`);
				},

				arrayExportExcelFile() {
					// 创建一个新的工作簿
					let workBook = XLSX.utils.book_new();

					const TestArray2Worksheet = [
						{
							"news_id": 51184,
							"title": "发布最新 iPhone X Review: Innovative future with real black technology",
							"source": "Netease phone"
						},
						{
							"news_id": 51183,
							"title": "Traffic paradise: How to design streets for people and unmanned vehicles in the future?",
							"source": "Netease smart",
							"link": "http://netease.smart/traffic-paradise/1235"
						},
						{
							"news_id": 51182,
							"title": "Teslamask's American Business Relations: The government does not pay billions to build factories",
							"source": "AI Finance",
						}
					]

					// 将 对象数组 换为 Sheet
					let workSheet0 = ExcelUtils.arrayToSheet(TestArray2Worksheet);

					// 把工作表添加到工作簿
					XLSX.utils.book_append_sheet(workBook, workSheet0, "Sheet1");

					// 导出 Excel 文件
					XLSX.writeFile(workBook, `example_${Date.now()}.xlsx`);
				},
			},
		});
	</script>
	<style></style>
</html>
